package com.test3;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * TreeSet集合的使用
 * Comparator：实现定制比较(比较器)
 * Comparable：可比较的
 */
public class ComparatorTest {
    public static void main(String[] args) {
        TreeSet<Students> students = new TreeSet<>(new Comparator<Students>() {
            @Override
            public int compare(Students o1, Students o2) {
                int n1 = o1.getAge()- o2.getAge();
                int n2 = o1.getName().compareTo(o2.getName());//比较两者名字，或是别的参数
                return n1 == 0?n2:n1;
            }
        });

        Students s1 = new Students("刘德华",20);
        Students s2 = new Students("黎明",20);
        Students s3 = new Students("张学友",18);
        students.add(s1);
        students.add(s2);
        students.add(s3);
        //[Students{name='张学友', age=18}, Students{name='刘德华', age=20}, Students{name='黎明', age=20}]
        //先按年龄，再按姓名顺序输出
        System.out.println(students);
    }
}
